<template>
  <div class="content">
    <div class="table-operation">
      <a-button type="primary" @click="updateTitleDep" icon="plus" v-if="QX.add">新增</a-button>
    </div>
    <a-table
      :columns="innerColumns"
      :data-source="innerData"
      :pagination="false"
      :loading="loading"
      :expanded-row-keys.sync="expandedRowKeys"
      :expandIcon="expandIcon"
      :expandIconColumnIndex="1"
      :scroll="{y: this.$getViewportSize().height-210 }"
      rowKey="organizationId">
          <span slot="action" slot-scope="text,record">
              <a v-if="QX.edit" @click="getOrgUpdate(record)"><a-icon class="iconBtn" type="edit"/>编辑</a>
              <a-divider v-if="QX.edit && QX.delete" type="vertical"/>
              <a-popconfirm
                            title="确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="removeOrganization(record)"
              >
                <a v-if="QX.delete"><a-icon class="iconBtn" type="delete"/>删除</a>
              </a-popconfirm>
            </span>
    </a-table>
    <a-drawer
      :closable="true"
      :title="modelDepTitle"
      :visible="visibleDep"
      @close="visibleDep=!visibleDep"
      :width="550">
      <a-spin class="submitLoading" :spinning="submitLoading">
        <a-form-model :model="formDep" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="formDep">
          <a-form-model-item label="组织名称" prop="organizationName">
            <a-input v-model="formDep.organizationName" placeholder="请输入组织名称" :maxLength="25" />
          </a-form-model-item>
          <a-form-model-item label="所属上级组织" prop="parentId">
            <a-tree-select
              v-model="formDep.parentId"
              placeholder="请选择所属上级组织"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="innerDataComputed"
              :replaceFields="{ key:'organizationId',title:'organizationName',value:'organizationId'}"
            >
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item label="组织联系电话" prop="contactNumber">
            <a-input v-model="formDep.contactNumber" placeholder="请输入组织联系电话" :maxLength="15" />
          </a-form-model-item>
          <a-form-model-item label="ERP部门编号" prop="erpDepId">
            <a-input v-model="formDep.erpDepId" placeholder="请输入ERP部门编号" :maxLength="10" />
          </a-form-model-item>
        </a-form-model>
        <div
          :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
          <a-button
            type="default"
            @click="visibleDep=!visibleDep"
          >
            取消
          </a-button>
          <a-button
            type="primary"
            @click="submitFormDep"
          >
            确认
          </a-button>
        </div>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script>
  import {
    getOrganization,
    getOrganizationList,
    insertOrganization,
    removeOrganization,
    updateOrganization,
  } from '@/api/organization';
  import preventBack from 'vue-prevent-browser-back';
  import TableTootip from '../../../components/TableTootip.vue'
  const innerColumns = [
    {
      title: '序号',
      width: '40px',
      align:'center',
      customRender: (text, record, index) => `${index + 1}`,
    },
    { title: '组织名称', width: '240px', dataIndex: 'organizationName',
      align:'left', key: 'organizationName' },
    { title: '组织联系电话', width: '110px', dataIndex: 'contactNumber',
      align:'center', key: 'contactNumber' },
    { title: '创建者', width: '90px', dataIndex: 'createUser',
      align:'center', key: 'createUser' },
    { title: '创建时间', width: '150px', dataIndex: 'createDatetime', align: 'center', key: 'createDatetime' },
    { title: '更新者', width: '90px', dataIndex: 'updateUser',
      align:'center', key: 'updateUser' },
    { title: '修改时间', width: '150px', dataIndex: 'updateDatetime', align: 'center', key: 'updateDatetime' },
    {
      title: '操作',
      width: 130,
      align: 'center',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right',
      scopedSlots: { customRender: 'action' },
    },
  ];
  const data = [];
  export default {
    name: 'Organization',
    mixins: [preventBack],//注入
    components:{
      TableTootip
    },
    data() {
      let validatePhone = (rule, value, callback) => {
        var isMob = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
        if(value){
          if (!isMob.test(value)) {
            callback(new Error('手机号码格式错误'));
          }
        }
        callback();
      };
      return {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
        selectDataOrg: [],
        formDep: {
          organizationName: '',
          contactNumber: '',
          organizationId: '',
          erpDepId:'',
          parentId: 0,
        },
        rules: {
          organizationName: [
            { required: true, message: '请输入组织名称', trigger: 'blur' },
          ],
          contactNumber: [
            {validator: validatePhone, trigger: 'blur'},
          ],
        },
        innerColumns,
        innerData:[],
        innerDataComputed:[],
        expandedRowKeys: [],
        loading: false,
        submitLoading: false,
        visibleDep: false,
        modelDepTitle: '新增组织',
        targetKeys: [],
        QX: {},
      };
    },
    watch: {
      visibleDep: function (newVal, oldVal) {
        if (!newVal) {
          this.restForm('formDep');
          this.formDep.organizationId = ''
        }
      },
    },
    mounted() {
      this.getOrganizationListPage();
    },
    methods: {
      //循环组织树
      dfs(root,id){
        root.disabled = false
        if(id&&root.organizationId == id){
          root.disabled = true
        }
        root.children.forEach((child) => {this.dfs(child,id)});
      },
      expandIcon(props) {
        if (props.record.children&&props.record.children.length) {
          if (props.expanded) {
            return (
              <span
            class="table-icon"
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
          >
          <a-icon type="down" />
              </span>
          );
          } else {
            return (
              <span
            class="table-icon"
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
          >
          <a-icon type="right" />
              </span>
          );
          }
        } else {//无数据-图标
          return <span style="margin-right:19px"></span>;
        }
      },
      //组织信息列表
      getOrganizationListPage() {
        this.loading = true;
        let operation = innerColumns[innerColumns.length - 1];
        getOrganizationList()
          .then(res => {
            if (res.result === 'success') {
              this.innerData = res.data;
              this.QX = res.QX;
              if (!this.QX.edit && !this.QX.delete) {
                if (operation.title === '操作') {
                  innerColumns.splice(innerColumns.length - 1, 1);
                }
              } else {
                if (operation.title !== '操作') {
                  innerColumns.push({
                    align: 'center',
                    title: '操作',
                    width: 150,
                    dataIndex: 'action',
                    key: 'action',
                    fixed: 'right',
                    scopedSlots: { customRender: 'action' },
                  });
                }
              }
            }
            this.loading = false;
          }
          ).catch(e => {
            this.loading = false;
          });
      },
      //修改组织信息
      getOrgUpdate(record) {
        this.modelDepTitle = '修改组织';
        this.loading = true
        getOrganization({ 'organizationId': record.organizationId })
          .then(res => {
            this.loading = false
            if (res.result === 'success') {
              this.visibleDep = true;
              this.$nextTick(() => {
                let organization = res.data;
                this.formDep.organizationName = organization.organizationName;
                this.formDep.contactNumber = organization.contactNumber
                this.formDep.parentId = organization.parentId;
                this.formDep.erpDepId = organization.erpId?organization.erpId:''
                this.formDep.organizationId = organization.organizationId;
                this.getInnerDataComputed(organization.organizationId)
              })
            } else if (res.result === 'failed') {
              this.getOrganizationListPage();
            }
          });
      },
      getInnerDataComputed(organizationId){
        var innerDataComputed = [{
          organizationId: 0,
          organizationName: '无上级组织',
          children:[]
        },...this.innerData];
        innerDataComputed.forEach(item=>{
          if(organizationId){
            this.dfs(item,organizationId)
          }else{
            this.dfs(item)
          }
        })
        this.innerDataComputed = innerDataComputed
      },
      /* 重置表单 */
      restForm(form) {
        this.$refs[form].resetFields();
      },
      // 保存组织信息
      submitFormDep() {
        this.$refs.formDep.validate(valid => {
          if (valid) {
            this.submitLoading = true
            if (this.formDep.organizationId == '') {
              insertOrganization(this.formDep)
                .then(res => {
                  if (res.result === 'success') {
                    this.visibleDep = false;
                    this.getOrganizationListPage();
                    this.$message.success('新增成功');
                  }
                  this.submitLoading = false
                });
            } else {
              updateOrganization(this.formDep)
                .then(res => {
                  if (res.result === 'success') {
                    this.visibleDep = false;
                    this.getOrganizationListPage();
                    this.$message.success('修改成功');
                  }
                  this.submitLoading = false
                });
            }
          }
        });
      },
      // 删除部门
      removeOrganization(record) {
        this.loading = true
        removeOrganization({ 'organizationId': record.organizationId })
          .then(res => {
              this.loading = false
            if (res.result === 'success') {
              this.$message.success('删除成功');
              this.getOrganizationListPage();
            }
          }
          );
      },
      updateTitleDep() {
        this.modelDepTitle = '新增组织';
        this.visibleDep = true;
        this.getInnerDataComputed()
      }
    },
  };

</script>

<style scoped>
  @import "../../../assets/css/maincss.css";
  form button {
    margin-left: 5px;
    margin-top: 0px;
  }

  .showForm input {
    color: black;
  }

  .form-company {
    margin: 0;
    /*padding: 3px;*/
  }

  .content {
    position: relative;
    overflow-y: auto;
    overflow-x: hidden;
    overflow: -moz-scrollbars-none;
    -ms-overflow-style: none;
  }
  .content::-webkit-scrollbar { width: 0 !important }
  /deep/.lay-content {
    padding-top: 0;
  }

  .ant-layout-content {
    padding-top: 0;
    margin-top: 0;
  }

  .treeScroll {
    position: absolute;
    top: -24px;
    /*left: 160px;*/
    bottom: 0;
    right: 5px;
    width: 20px;
    border: 1px solid #f0f2f5;
    background-color: #f0f2f5;
  }

  .lay-drawer-form {
    margin-right: 30px;
    margin-top: 30px;
  }

  .lay-drawer-form input {
    width: 450px;
  }

  /deep/.lay-drawer-form .lay-drawer-form {
    width: 450px;
  }

  /deep/.lay-drawer-form .ant-form-item-control {
    width: 600px;
  }
</style>
